<?php

require_once("config.php");
require_once("utils.php");
// input parameters: item_id, tag
/* add tag to item
 * if !exists(tag) -> create(tag)
 * insert into map_t item<->tag
 * 
 * 
 */
$item_id=sqlite_escape_string($_POST['item_id']);
$tag_type=sqlite_escape_string($_POST['tag_type']);
$tag_value=sqlite_escape_string($_POST['tag_value']);
$tag=$tag_type . "::" . $tag_value;
echo $tag . " " . $item_id . "<br>";


$db=new SQLite3($dbfilename);
$query="SELECT * FROM tag_t WHERE value='$tag'";
$results=$db->query($query);
$res = $results->fetchArray(SQLITE3_ASSOC);

if (!empty($res)) { // tag already exists
	$tag_id=$res['tag_id'];
	echo "tag " . $tag . "already exists with tag_id " . $tag_id . "<br>";
} else {
	echo "adding tag " . $tag . " as new<br>";
	$query="INSERT INTO tag_t (value) VALUES ('$tag')";	
	$results=$db->query($query);
	// FIXME: ezt ki lehet-e szedni az előző lekérdezésből?
	$query="SELECT * FROM tag_t WHERE value='$tag'";
	$results=$db->query($query);
	$res = $results->fetchArray(SQLITE3_ASSOC);
	$tag_id=$res['tag_id'];
}

// insert into map_t item<->tag

$query="SELECT * FROM map_t WHERE item_id='$item_id' AND tag_id='tag_id';";
$results=$db->query($query);
print_r($results);
var_dump($results);
$res = $results->fetchArray(SQLITE3_ASSOC);
if (!empty($res)) { // mapping already exists
	// do nothing
	echo "mapping already exists<br>";
} else {
	$query="INSERT INTO map_t (item_id, tag_id) VALUES ('$item_id', '$tag_id');";	
	$db->query($query);
} 

$db->close();